package com.naiterui.ehp.bs.patient.repository;

import java.math.BigInteger;
import java.util.Date;
import java.util.List;
import java.util.Set;

import org.springframework.data.jpa.repository.Modifying;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import com.naiterui.common.repository.core.BaseJpaRepository;
import com.naiterui.ehp.bp.domain.Patient;

/**
 * <pre>
 * 患者基础信息持久化实现
 * </pre>
 *
 * @author fangguanhong
 * @date 2020/4/10 下午4:44
 * @since 1.0.0
 */
@Repository
public interface IApPatientRepository extends BaseJpaRepository<Patient, Long> {

    Patient findFirstByOpenId(String openId);

    Patient findFirstByUnionId(String unionId);

    @Query(nativeQuery = true, value = "select r.doctor_id from patient_personal_doctor r,doctor d where r.patient_id = ?1 and r.doctor_id = d.id ")
    List<BigInteger> getPersonalIds(Long patientId);

    @Query(nativeQuery = true, value = "select r.doctor_id from patient_personal_doctor r,doctor d where r.patient_id = ?1 and r.doctor_id = d.id " +
            "and d.account_status = 0")
    List<BigInteger> getPersonalIdsByAccountStatus(Long patientId);

    Patient findFirstByPhone(String phone);

    @Modifying(clearAutomatically = true)
    @Query("update Patient set cancel = :cancel where unionId = :unionId")
    void updatePatientByUnionId(@Param("unionId") String unionId, @Param("cancel") int cancel);

    List<Patient> findByIdIn(Set<Long> ids);

    @Override
    @Modifying
    Patient saveOrUpdate(Patient patient);

    List<Patient> findByChangedAtBetween(Date start, Date end);

    Patient findFirstByMiniOpenId(String miniAppId);
}
